﻿using Hippo.Framework.Model;
using Common.Logging;

namespace Hippo.Console.Lib.Services
{
    using System;
    using System.ServiceModel;
    using System.ServiceModel.Channels;
    using System.IO;
    using System.Xml.Linq;

    [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)]
    public class ControlService : IControlService
    {
        private static readonly ILog Log = LogManager.GetCurrentClassLogger();

        public event EventHandler<AgentCallbackEventArgs> AgentRegistered;

        public virtual void RegisterAgent(string clientName)
        {
            var callbackChannel = OperationContext.Current.GetCallbackChannel<IControlServiceCallback>();
            if (callbackChannel == null)
            {
                throw new InvalidChannelBindingException("Failed to get the callback channel for the agent. This might be because of faulty third party agents.");
            }

            InvokeAgentRegistered(new AgentCallbackEventArgs(clientName, callbackChannel));
            Console.WriteLine("Agent registered with name " + clientName + ".");
        }

        public void RegisterTestResult(TestResult result)
        {
            // TODO There should be some extensibility model in here
            Log.InfoFormat("{0} {1}: {2} {3} ms", result.AgentName, result.TestName, result.Resource, result.ElapsedMilliseconds);

            /* Temporary code */
            XDocument doc = new XDocument();
            if (File.Exists("report.xml"))
            {
                doc = XDocument.Load("report.xml");
            }

            var root = doc.Root;
            if (root == null)
            {
                root = new XElement("report");
                doc.Add(root);
            }

            root.Add(new XElement("testResult",
                new XAttribute("elapsedMilliseconds", result.ElapsedMilliseconds)));

            root.Save("report.xml");
        }

        protected virtual void InvokeAgentRegistered(AgentCallbackEventArgs e)
        {
            var handler = AgentRegistered;
            if (handler != null)
            {
                handler(this, e);
            }
        }

        public void SignalTestRunComplete(Guid id)
        {
            throw new NotImplementedException();
        }
    }
}
